import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import RegisterView from '@/views/RegisterView.vue'
import UserListView from '@/views/UserListView.vue'
import UserProfileView from '@/views/UserProfileView.vue'
import NotFound from '@/views/NotFound.vue'
import store from '../store'

const routes = [
  {
    path: '/myblog/',
    name: 'home',
    component: HomeView,
    meta: {
      requireAuth: true,
    }
  },
  {
    path: '/myblog/login/',
    name: 'login',
    component: LoginView,
    meta: {
      requireAuth: false,
    }
  },
  {
    path: '/myblog/register/',
    name: 'register',
    component: RegisterView,
    meta: {
      requireAuth: false,
    }
  },
  {
    path: '/myblog/userlist/',
    name: 'userlist',
    component: UserListView,
    meta: {
      requireAuth: true,
    }
  },
  {
    path: '/myblog/userprofile/:userId/',
    name: 'userprofile',
    component: UserProfileView,
    meta: {
      requireAuth: true,
    }
  },
  {
    path: '/myblog/404/',
    name: '404',
    component: NotFound,
    meta: {
      requireAuth: false,
    }
  },
  {
    path: '/myblog/:catchAll(.*)/',
    redirect: "/myblog/404/"
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  if(to.meta.requireAuth && !store.state.user.is_login) {
    next({name: 'login'});
  }else {
    next();
  }
})



export default router
